# SETWD ===========================
rm(list=ls())


# LIBRARIES ===========================

library(tidyverse)
library(foreign)
library(stargazer)
library(lmtest)
library(multiwayvcov)
library(ggrepel)
library(stringr)

# FIG 1. Cases of Democratic Erosion, 1995-2020 ===========================

erosion <- read.csv("data/erosion-figure.csv")

erosion <- erosion%>%
  mutate(start=
           (as.numeric(str_sub(initial.election,1,2))-1)/12+
           as.numeric(str_sub(initial.election,4,7)),
         end=
           (as.numeric(str_sub(oust.election,1,2))-1)/12+
           as.numeric(str_sub(oust.election,4,7)))

erosion %>%
  ggplot(aes(y=reorder(country.name,end,max)))+
  geom_segment(aes(x=start,xend=end,yend=reorder(country.name,end,max)),
               color="black")+
  ylab("Country")+
  xlab("Year")+
  theme_bw()

ggsave(filename = "figures/erosion-seg-12_05_24.png",width=4,height=4.2)


# SAMPLE INFO ===========================

# 23 spells of erosion in 22 countries:
length(erosion$country.name)
length(unique(erosion$country.name))

# average duration: 9 years
erosion%>%
  mutate(length=end-start)%>%
  summarise('Average Duration of Erosion (years)'=round(mean(length)))

# 68 national elections under erosion
dfgi <- read.csv("data/sve-08_04_24.csv",stringsAsFactors = F)
dfgi%>%
  filter(erosion.strict==1)%>%
  summarise('Election Years under Erosion'=sum(elec.any))

